package com.lovo.manage_back.auth;

import com.lovo.manage_back.bean.Authority;
import com.lovo.manage_back.bean.User;
import com.lovo.manage_back.result.GlobalHandleException;
import com.lovo.manage_back.result.Result;
import com.lovo.manage_back.result.ResultCode;
import com.lovo.manage_back.service.UserService;
import com.lovo.manage_back.util.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class JWTRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录的用户
        User user = (User) principalCollection.getPrimaryPrincipal();
        //通过SimpleAuthenticationInfo做授权
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        List<Authority> authorities = user.getAuthorities();
        authorities.forEach(item -> simpleAuthorizationInfo.addStringPermission(item.getName()));
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getPrincipal();
        if(token == null){
            return new SimpleAuthenticationInfo(null,"",getName());
        }
        User user = null;
        try {
            String username = JWTUtil.getAudience(token);
            user = userService.getUserByName(username);
            JWTUtil.verifyToken(token,user.getPwd());
        } catch (GlobalHandleException e) {
//            return new SimpleAuthenticationInfo(Result.fail(e.getResultCode()),token,getName());
            user = null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,token,getName());
        return simpleAuthenticationInfo;
    }
}
